#include "Grilla.h"

#include <stdexcept>

#include <GL\glew.h>
#include <GL\freeglut.h>


Grilla::Grilla(){
	// Los vertices del borde
	this->m_vertices_borde[0] = glm::vec3(1.0f, 1.0f, 0.0f);
	this->m_vertices_borde[1] = glm::vec3(-1.0f, 1.0f, 0.0f);
	this->m_vertices_borde[2] = glm::vec3(-1.0f, -1.0f, 0.0f);
	this->m_vertices_borde[3] = glm::vec3(1.0f, -1.0f, 0.0f);

	// Los vertices del centro
	this->m_vertices_cruz[0] = glm::vec3(0.0f, 1.0f, 0.0f);
	this->m_vertices_cruz[1] = glm::vec3(0.0f, -1.0f, 0.0f);
	this->m_vertices_cruz[2] = glm::vec3(1.0f, 0.0f, 0.0f);
	this->m_vertices_cruz[3] = glm::vec3(-1.0f, 0.0f, 0.0f);

	// El resto de la grilla
	int pos = -1;
	for (int i = 0; i< 9; ++i){
		GLfloat x = -0.8f + i * 0.2f;
		if (x == 0.0f) continue;

		this->m_vertices_red[++pos] = glm::vec3(x, 1.0f, 0.0f);
		this->m_vertices_red[++pos] = glm::vec3(x, -1.0f, 0.0f);
	}
	for (int i = 0; i< 9; ++i){
		GLfloat y = -0.8f + i * 0.2f;
		if (y == 0.0f) continue;

		this->m_vertices_red[++pos] = glm::vec3(1.0f, y, 0.0f);
		this->m_vertices_red[++pos] = glm::vec3(-1.0f, y, 0.0f);
	}
}


void Grilla::init() {
	Renderizable::init( glm::vec3(0.0f, 0.0f, 0.0f), "SimpleShader.vert", "SimpleShader.frag");
}


void Grilla::renderizar(const glm::mat4 &matVista, const glm::mat4 &matProyeccion, const glm::mat4 &matModelo) const {
	// Carga el shader
	const GLuint shaderProgramID = Renderizable::cargarShaderProgram();

	// Bindea el color
	GLint locColor = glGetUniformLocation(shaderProgramID, "color");
	if (locColor == -1) throw std::runtime_error("No existe el parametro 'color' en el shader");

	// Empieza a dibujar todo
	glEnableClientState(GL_VERTEX_ARRAY);

	// Las matrices de transformacion
	Renderizable::cargarMatricesTransformacion(matVista, matProyeccion, matModelo);

	// El borde de la figura
	glUniform3f(locColor, 1.0f, 0.0f, 0.0f);
	glVertexPointer(3, GL_FLOAT, 0, this->m_vertices_borde);
	glDrawArrays(GL_LINE_LOOP, 0, 4);
	
	// El centro de la figura
	glUniform3f(locColor, 0.0f, 1.0f, 0.0f);
	glVertexPointer(3, GL_FLOAT, 0, this->m_vertices_cruz);
	glDrawArrays(GL_LINES, 0, 4);

	// La red de la grilla
	glUniform3f(locColor, 0.0f, 0.0f, 1.0f);
	glVertexPointer(3, GL_FLOAT, 0, this->m_vertices_red);
	glDrawArrays(GL_LINES, 0, 32);

	glDisableClientState(GL_VERTEX_ARRAY);
}
